

import 'dart:ffi';
import 'dart:io';

import 'package:ble2318_plugin/ble2318_plugin.dart';
import 'package:ble2318_plugin_example/models.dart';
import 'package:ble2318_plugin_example/util/app_all_value.dart';
import 'package:ble2318_plugin_example/util/event_bus.dart';
import 'package:csv/csv.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_share/flutter_share.dart';
import 'package:get/get.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

///2318设备的PPG和EDA原始数据获取
class PpgEda2318Page extends StatefulWidget {
  const PpgEda2318Page({Key? key}) : super(key: key);

  @override
  State<PpgEda2318Page> createState() => _PpgEda2318PageState();
}

class _PpgEda2318PageState extends State<PpgEda2318Page> {
  // -1 未选择 1 PPG 2 EDA
  int type  = 1;
  String btnText1 = "PPG(选中)";
  String btnText2 = "EDA";

  String savePath = "";

  List<PpgEdaNewCsvInfo> datas = [];

  bool isStart = false;


  var logController = TextEditingController();
  AppAllValueController controller = Get.find();
  var s = "";
  @override
  void initState() {
    super.initState();
    checkStorage();
    // getSavePath();
    EventBus().on('dataByteCallBack', (arg) {
      //
      Uint8List list = arg;
      // List<int> list = [0x3C,0x02,0x48,0x6D,0x04,0x00,0x56,0x09,0x04,0x00,0x6A,0x8A,
      //   0xFF,0xFF,0x16,0x51,0xFE,0xFF,0xCB,0x7A,0x3A,0x00,0x56,0xE3,0x88,0x2A,0x2D,0x00];
      setState(() {
        s = "";
        list.toList().forEach((element) {
          var v = element.toRadixString(16).toUpperCase();
          s+= v.length == 1 ?'0$v ':'$v ';
        });
        s = s.substring(0,s.length - 1);
        if(list.length > 16){
          List<int> eda1Shi = [list[2],list[3],list[4],list[5]];
          List<int> eda1Xu = [list[6],list[7],list[8],list[9]];
          List<int> eda2Shi = [list[10],list[11],list[12],list[13]];
          List<int> eda2Xu = [list[14],list[15],list[16],list[17]];
          List<int> r = [list[18],list[19],list[20],list[21]];
          DateTime time = DateTime.now();
          PpgEdaNewCsvInfo info = PpgEdaNewCsvInfo(time: '${time.year}-${time.month}-${time.day} ${time.hour}:${time.minute}:${time.second}',
            eda1Shi: '${symbol(ResolveUtil.valueHou(eda1Shi))}',
            eda1Xu: '${symbol(ResolveUtil.valueHou(eda1Xu))}',
            eda2Shi: '${symbol(ResolveUtil.valueHou(eda2Shi))}',
            eda2Xu: '${symbol(ResolveUtil.valueHou(eda2Xu))}',
            resistance: '${ResolveUtil.valueHou(r)}',
          );
          datas.add(info);
          // print('111111: ${info.toString()}\n');
        }
        logController.text = '$s\n${logController.text} ';
      });
      if(list.length == 16 && list[2].toInt() == 0){
        getSavePath();
      }
    });

  }


  ///获取保存的路径
  void getSavePath(){
    getTemporaryDirectory()
        .then((tempDir){
          savePath = '${tempDir.path}/test-${DateTime.now().toString().split('.')[0].replaceAll(' ', '')}.csv';
          saveFile();
        });
  }

  ///检测存储权限
  void checkStorage() async{
    PermissionStatus locationStatus = await Permission.storage.status;
    if (locationStatus.isDenied) {
      if (await Permission.location.request().isGranted) {
      }
    }
  }

  void saveFile() async{
    print('saveFile: ${datas.length}');
    if(datas.isNotEmpty){
      List<List<dynamic>> rows = [];
      rows.add(["time","EDA1 Real part data","EDA1 Virtual part data","EDA2 Real part data","EDA2 Virtual part data",'resistance value']);
      for (var map in datas) {
        rows.add([map.time,map.eda1Shi,map.eda1Xu,map.eda2Shi,map.eda2Xu,map.resistance]);
      }
      String csv = const ListToCsvConverter().convert(rows);
      File file = File(savePath);
      await file.writeAsString(csv);
      setState(() {
      });
      print("File exported successfully!");
    }
  }




  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("PPG和EDA(2318)".tr),
      ),
      body: GestureDetector(
        onTap: (){
          // Get.back();
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: Container(
          color: Colors.white,
          child: Column(
            mainAxisSize: MainAxisSize.max,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Expanded(child: Container(
                    margin: const EdgeInsets.only(left: 10,right: 10,top: 20),
                    child: ElevatedButton(
                      child: Text(btnText1.tr),
                      onPressed: (){
                        type = 1;
                        setState(() {
                          btnText1 = "PPG(选中)";
                          btnText2 = "EDA";
                        });
                      },
                    ),
                  )),
                  Expanded(child: Container(
                    margin: const EdgeInsets.only(left: 10,right: 10,top: 20),
                    child: ElevatedButton(
                      child: Text(btnText2.tr),
                      onPressed: (){
                        type = 2;
                        setState(() {
                          btnText1 = "PPG";
                          btnText2 = "EDA(选中)";
                        });
                      },
                    ),
                  ))
                ],
              ),
              Container(
                margin: const EdgeInsets.only(left: 10,right: 10,top: 10),
                child: Row(
                  children: [
                    Expanded(
                      child: Text('path:$savePath'),
                    ),
                    Container(
                      width: 100,
                      margin: EdgeInsets.only(left: 10),
                      child: ElevatedButton(
                        child: Text('分享'.tr),
                        onPressed: () async {
                          if(isStart){
                            return;
                          }
                          if(savePath.isNotEmpty){
                            FlutterShare.shareFile(title: 'data', filePath: savePath);
                          }
                        },
                      ),
                    )
                  ],
                ),
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Expanded(child: Container(
                    margin: const EdgeInsets.only(left: 10,right: 10,top: 10),
                    child: ElevatedButton(
                      child: Text('开始'.tr),
                      onPressed: (){
                        if(type == -1){
                          controller.showContentDialog("未选择类型");
                        }
                        isStart = true;
                        datas.clear();
                        controller.writeData(BleSDK.SetPpgAndEda(type, true));
                      },
                    ),
                  )),
                  Expanded(child: Container(
                    margin: const EdgeInsets.only(left: 10,right: 10,top: 10),
                    child: ElevatedButton(
                      child: Text('关闭'.tr),
                      onPressed: (){
                        if(type == -1){
                          controller.showContentDialog("未选择类型");
                        }
                        isStart = false;
                        controller.writeData(BleSDK.SetPpgAndEda(type, false));
                      },
                    ),
                  )),
                  Expanded(child: Container(
                    margin: const EdgeInsets.only(left: 10,right: 10,top: 10),
                    child: ElevatedButton(
                      child: Text('清除控制台'.tr),
                      onPressed: (){
                        logController.text = '';
                      },
                    ),
                  ))
                ],
              ),
              Expanded(
                child: ListView(
                  padding: const EdgeInsets.only(left: 10,right: 10),
                  shrinkWrap: true,
                  children: [
                    TextField(
                      controller: logController,
                      maxLines: null,
                      enabled: false,
                    )
                  ],),
              )
            ],
          ),
        ),
      ),
    );
  }

  ///4个字节的有符号转换
  int symbol(int value){
    int vv = value;
    if(value > 2147483647){
      vv -= 4294967295;
    }
    return vv;
  }

  @override
  void dispose() {
    super.dispose();
    EventBus().off('dataByteCallBack');
  }

}
